#include <logbase.h>
#include <errno.h>
#include <stdarg.h>
#include <cstring.h>
#include <crcCalc.h>
#include <genrand.h>
#include <typecvrt.h>
#include <hexstr.h>
#include <systime.h>

struct mychkStc
{
    uint64_t wCounter;
    uint64_t rCounter;
    uint64_t buflen;
};

static /*volatile*/ struct mychkStc globalVal;
static int globalRunFlg = 0;
#define MY_CHECK_USE_MUTEX_FLG 0
#if MY_CHECK_USE_MUTEX_FLG
static pthread_mutex_t globalMutex;
#endif
void *mythrd(void *p)
{
    while (globalRunFlg)
    {
#if MY_CHECK_USE_MUTEX_FLG
        pthread_mutex_lock(&globalMutex);
#endif
        if (globalVal.buflen > 0)
        {
            globalVal.buflen--;
            globalVal.rCounter++;
        }
#if MY_CHECK_USE_MUTEX_FLG
        pthread_mutex_unlock(&globalMutex);
#endif
        // usleep(100);
    }
    while (globalVal.buflen > 0)
    {
        globalVal.buflen--;
        globalVal.rCounter++;
    }
    return NULL;
}

int main()
{
    pthread_t tmpthrd;
    sysTmTp tmptmr;
    memset((void *)&globalVal, 0, sizeof(globalVal));
    globalRunFlg = 1;
    pthread_create(&tmpthrd, NULL, mythrd, NULL);
#if MY_CHECK_USE_MUTEX_FLG
    pthread_mutex_init(&globalMutex, NULL);
#endif
    sysTmBeg(tmptmr);
    while (sysTmRunSec(tmptmr) < 1)
    {
#if MY_CHECK_USE_MUTEX_FLG
        pthread_mutex_lock(&globalMutex);
#endif
        {
            globalVal.buflen++;
            globalVal.wCounter++;
        }
#if MY_CHECK_USE_MUTEX_FLG
        pthread_mutex_unlock(&globalMutex);
#endif
        // usleep(100);
    }
    globalRunFlg = 0;
    pthread_join(tmpthrd, NULL);
#if MY_CHECK_USE_MUTEX_FLG
    pthread_mutex_destroy(&globalMutex);
#endif
    logdebugc("wc=%ld,rc=%ld", globalVal.wCounter, globalVal.rCounter);
    return 0;
}
